//
//  EBookDetailViewController.swift
//  clreader
//
//  Created by colin on 2019/3/12.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit

// 电子书详情
class EBookDetailViewController: CLBaseViewController {

    private var goods_id = 0
    private var goodsInfo = JSONObject() {
        didSet {
            self.refresh()

            // 是否收藏
            if let collect = self.goodsInfo["collect"] as? Int,collect > 0 {
                self.isCollect = true
            } else {
                self.isCollect = false
            }
        }
    }
    
    private var isCollect = false {
        didSet {
            if self.isCollect {
                self.buttonLike.setImage(UIImage(named: "button_like_checked"), for: .normal)
            } else {
                self.buttonLike.setImage(UIImage(named: "button_like_normal"), for: .normal)
            }
        }
    }
    
    private lazy var topBar = CLNavigationBar()
    private lazy var buttonLike = UIButton(type: .custom) // 喜欢按钮
    
    private var bottomBar:UIView?
    
    private lazy var detailTableView = UITableView(frame: CGRect.zero, style: .grouped)
    private lazy var cellHeights = [IndexPath:CGFloat]()
    
    convenience init(goods_id:Int) {
        self.init()
        self.goods_id = goods_id
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        //topBar
        self.topBar.do {
            $0.title = ""
            $0.backHandle = { [weak self] in
                self?.navigationController?.popViewController(animated: true)
            }
            
            let buttonShare = UIButton(type: .custom).then {
                $0.setImage(UIImage(named: "button_share"), for: .normal)
            }
            let itemShare = CLNavigationBar.Item(customView: buttonShare, viewHandle: {
                print("分享")
            })
            
            self.buttonLike.setImage(UIImage(named: "button_like_normal"), for: .normal)
            let itemLike = CLNavigationBar.Item(customView: self.buttonLike, viewHandle: { [weak self] in
                
                guard let `self` = self else { return }
                
                // 判断是否已经登录
                if !AccountManager.shared.isLogin {
                    let loginController = LoginViewController()
                    let navController = CLNavigationController(rootViewController: loginController)
                    self.present(navController, animated: true, completion: nil)
                    return
                }
                
                let token = AccountManager.shared.token
                if !self.isCollect {
                    self.hud.showProgress()
                    _ = Router.addCollect(goods_id: self.goods_id, token: token).request({ (response:RequestResponse<JSONObject>) in
                        
                        self.hud.hide()
                        
                        if case .success = response {
                            self.isCollect = true
                        }
                        
                        if case .failure(_, let message) = response {
                            self.hud.showText(message)
                        }
                        
                    })
                } else {
                    self.hud.showProgress()
                    _ = Router.removeCollect(goods_id: self.goods_id, token: token).request({ (response:RequestResponse<JSONObject>) in
                        
                        self.hud.hide()
                        
                        if case .success = response {
                            self.isCollect = false
                        }
                        
                        if case .failure(_, let message) = response {
                            self.hud.showText(message)
                        }
                        
                    })
                }
                
            })
            
            $0.rightItems = [itemLike, itemShare]
        }
        self.topBar.show(inView: self.view)
        
        // 注册cell
        self.detailTableView.do {
            $0.register(CellHeader.self, forCellReuseIdentifier: CellHeader.reuseId)
            $0.register(CellIntro.self, forCellReuseIdentifier: CellIntro.reuseId)
            $0.register(CellCopyright.self, forCellReuseIdentifier: CellCopyright.reuseId)
            $0.register(CellExpand.self, forCellReuseIdentifier: CellExpand.reuseId)
        }
        
        self.detailTableView.do {
            $0.dataSource = self
            $0.delegate = self
        }
        
        self.detailTableView.do {
            $0.contentInsetAdjustmentBehavior = .never
            $0.backgroundColor = UIColor(hex: "f2f4f5")
            $0.estimatedSectionHeaderHeight = CGFloat.leastNormalMagnitude
            $0.estimatedSectionFooterHeight = CGFloat.leastNormalMagnitude
            $0.estimatedRowHeight = CGFloat.leastNormalMagnitude
            $0.sectionHeaderHeight = CGFloat.leastNormalMagnitude
            $0.sectionFooterHeight = CGFloat.leastNormalMagnitude
            $0.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNormalMagnitude))
            $0.separatorStyle = .none
            $0.showsVerticalScrollIndicator = false
        }
        
        // 加载数据
        self.loadGoodInfo()
    }

}

extension EBookDetailViewController {
    
    private func refresh() {
        
        self.detailTableView.removeFromSuperview()
        self.bottomBar?.removeFromSuperview()
        
        // 底部
        var bottomBar:UIView?
        
        // 纸书购买链接
        var buy_url = ""
        if let value = self.goodsInfo["buy_url"] as? String, !value.isEmpty {
            buy_url = value
        }
        
        // 是否免费
        var is_free = false
        if let value = self.goodsInfo["is_free"] as? Int, value == 1 {
            is_free = true
        }
        
        // 是否已经购买
        var is_buy = false
        if let value = self.goodsInfo["is_buy"] as? Int, value == 1 {
            is_buy = true
        }
        
        // 价格
        var price = 0.0
        if let value = self.goodsInfo["price"] as? Double {
            price = value
        }
        
        if !buy_url.isEmpty || (!is_free && !is_buy) {
            
            let bottomBar_ = UIView().then {
                $0.backgroundColor = UIColor.white
            }
            bottomBar = bottomBar_
            
            var buttons = [UIButton]()
            
            // 试读or阅读
            let buttonRead_ = UIButton(type: .custom).then {
                
                if !is_free && !is_buy {
                    $0.setTitle("试读", for: .normal)
                } else {
                    $0.setTitle("阅读", for: .normal)
                }
                
                $0.addTarget(self, action: #selector(self.actionRead(_:)), for: .touchUpInside)
            }
            buttons.append(buttonRead_)
            
            // 购买纸质书
            if !buy_url.isEmpty {
                let buttonBuyPaper_ = UIButton(type: .custom).then {
                    $0.setTitle("纸书购买", for: .normal)
                    $0.addTarget(self, action: #selector(self.actionBuyPaper(_:)), for: .touchUpInside)
                }
                buttons.append(buttonBuyPaper_)
            }
            
            // 购买
            if !is_free && !is_buy {
                let buttonBuy_ = UIButton(type: .custom).then {
                    $0.setTitle("购买 \(price)", for: .normal)
                    $0.addTarget(self, action: #selector(self.actionBuy(_:)), for: .touchUpInside)
                }
                buttons.append(buttonBuy_)
            }
            
            // 添加按钮
            var pre:UIButton?
            for index in 0 ..< buttons.count {
                let button = buttons[index]
                bottomBar_.addSubview(button)
                button.snp.makeConstraints { (make) in
                    if let pre_ = pre {
                        make.left.equalTo(pre_.snp.right)
                        make.width.equalTo(pre_.snp.width)
                    } else {
                        make.left.equalToSuperview()
                    }
                    
                    if index == buttons.count - 1 {
                        make.right.equalToSuperview()
                    }
                    
                    make.top.bottom.equalToSuperview()
                }
                pre = button
            }
            
            // 按钮样式
            if buttons.count == 1 {
                let button = buttons[0]
                button.setTitleColor(UIColor.white, for: .normal)
                button.backgroundColor = UIColor(hex: "AE1600")
            }
            
            if buttons.count == 2 {
                let button1 = buttons[0]
                button1.setTitleColor(UIColor.black, for: .normal)
                button1.backgroundColor = UIColor.white
                
                let button2 = buttons[1]
                button2.setTitleColor(UIColor.white, for: .normal)
                button2.backgroundColor = UIColor(hex: "AE1600")
            }
            
            if buttons.count == 3 {
                let button1 = buttons[0]
                button1.setTitleColor(UIColor.black, for: .normal)
                button1.backgroundColor = UIColor.white
                
                let button2 = buttons[1]
                button2.setTitleColor(UIColor.white, for: .normal)
                button2.backgroundColor = UIColor(hex: "00ff00")
                
                let button3 = buttons[2]
                button3.setTitleColor(UIColor.white, for: .normal)
                button3.backgroundColor = UIColor(hex: "AE1600")
            }
            
            self.view.addSubview(bottomBar_)
            bottomBar_.snp.makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.height.equalTo(50.0)
                make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
            }
            
            self.bottomBar = bottomBar_
        }

        // 内容
        self.view.addSubview(self.detailTableView)
        self.detailTableView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(topBar.snp.bottom)
            if let bottomBar_ = bottomBar {
                make.bottom.equalTo(bottomBar_.snp.top)
            } else {
                make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
            }
        }

    }
    
    private func loadGoodInfo() {
        self.hud.showProgress()
        let token = AccountManager.shared.token

        _ = Router.goods_info(goods_id: self.goods_id, token: token).request { [weak self] (response:RequestResponse<JSONObject>) in
            
            self?.hud.hide()
            
            if case .success(let successData,_) = response {
                if let goodsInfo_ = successData {
                    self?.goodsInfo = goodsInfo_
                    self?.detailTableView.reloadData()
                }
            }
            
            if case .failure(_,let message) = response {
                self?.hud.showText(message)
            }
        }
    }
    

    // MARK - 试读or阅读
    @objc private func actionRead(_ sender:Any) {
        if let goods_id_ = self.goodsInfo["goods_id"] as? Int, goods_id_ > 0 {
            let controller = CLReadViewController(bookId: goods_id_, chapterId: nil)
            self.show(controller, sender: nil)
        } else {
            self.hud.showText("未找到图书信息")
        }
    }
    
    // MARK - 纸书购买
    @objc private func actionBuyPaper(_ sender:Any) {
        let buyUrl = self.goodsInfo["buy_url"] as? String
        let controller = CLWebViewController(urlString: buyUrl)
        self.show(controller, sender: nil)
    }
    
    @objc private func actionBuy(_ sender:Any) {
        self.hud.showText("购买")
    }
    
}

extension EBookDetailViewController : UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        if !self.goodsInfo.isEmpty {
            return 4
        } else {
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 3 {
            //拓展阅读
            if let goods = self.goodsInfo["goodsList"] as? [JSONObject] {
                return goods.count
            } else {
                return 0
            }
        } else {
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 3 {
            let cell = tableView.dequeueReusableCell(withIdentifier: CellExpand.reuseId) as! CellExpand
            if let goods = self.goodsInfo["goodsList"] as? [JSONObject], goods.count > indexPath.row {
                cell.refresh(data: goods[indexPath.row])
            } else {
                cell.refresh(data: nil)
            }
            self.cellHeights[indexPath] = cell.cellHeight
            return cell
        } else if indexPath.section == 2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: CellCopyright.reuseId) as! CellCopyright
            cell.refresh(data: self.goodsInfo)
            self.cellHeights[indexPath] = cell.cellHeight
            return cell
        } else if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: CellIntro.reuseId) as! CellIntro
            cell.refresh(data: self.goodsInfo, heightChangedHandle: { [weak self] (height_) in
                self?.cellHeights[indexPath] = height_
                DispatchQueue.main.async {
                    self?.detailTableView.reloadData()
                }
            })
            self.cellHeights[indexPath] = cell.cellHeight
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: CellHeader.reuseId) as! CellHeader
            cell.refresh(data: self.goodsInfo)
            self.cellHeights[indexPath] = cell.cellHeight
            return cell
        }
    }

}

extension EBookDetailViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if let height = self.cellHeights[indexPath] {
            return height
        } else {
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if !self.goodsInfo.isEmpty && section > 0 {
            let headerView = UIView().then {
                let tagView = UIView()
                tagView.backgroundColor = UIColor(hex: "AE1600")
                $0.addSubview(tagView)
                tagView.snp.makeConstraints({ (make) in
                    make.left.equalToSuperview()
                    make.size.equalTo(CGSize(width: 3.0, height: 20.0))
                    make.centerY.equalToSuperview()
                })
                
                let labelTitle = UILabel().then {
                    $0.textColor = UIColor(hex: "343434")
                    $0.font = UIFont.systemFont(ofSize: 17.0, weight: .bold)
                    if section == 3 {
                        $0.text = "拓展阅读"
                    } else if section == 2 {
                        $0.text = "图书版权"
                    } else if section == 1 {
                        $0.text = "简介"
                    }
                }
                $0.addSubview(labelTitle)
                labelTitle.snp.makeConstraints({ (make) in
                    make.left.equalTo(tagView.snp.right).offset(15.0)
                    make.centerY.equalToSuperview()
                })
                
            }
            return headerView
        } else {
            return nil
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if !self.goodsInfo.isEmpty && section > 0 {
            return 40.0
        } else {
            return CGFloat.leastNormalMagnitude
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 3 {
            if let goods = self.goodsInfo["goodsList"] as? [JSONObject], goods.count > indexPath.row {
                let goodInfo = goods[indexPath.row]
                if let sourceType = SourceType(type: goodInfo["type"] as? Int),
                    let goods_id = goodInfo["goods_id"] as? Int {
                    if sourceType == .电子书 {
                        let controller = EBookDetailViewController(goods_id: goods_id)
                        self.show(controller, sender: nil)
                    } else {
                        let controller = SourceDetailViewController(sourceType: sourceType, goods_id: goods_id)
                        self.show(controller, sender: nil)
                    }
                }
            }
        }
        
        tableView.deselectRow(at: indexPath, animated: true)
    }
}
